# 读取本地FCL文件夹内存储的信息的模块

import json

from Config import config
from Logging import *

game_local_dict_ = open(file=config.game_versions_json_path, encoding="utf-8", mode="r")
game_local_dict = dict(json.load(game_local_dict_))
game_local_dict_.close()

FCL_setting_dict_ = open(file=config.FCL_setting_json_path, encoding="utf-8", mode="r")
FCL_setting_dict = dict(json.load(FCL_setting_dict_))
FCL_setting_dict_.close()


versions_features_dict_ = open(file=config.versions_features_json_path, encoding="utf-8", mode="r")
versions_features_dict = dict(json.load(versions_features_dict_))
versions_features_dict_.close()


def sort_(elem: dict):
    return str(elem["version"])


class local_files:

    def game_versions_list(self: int):
        """
        此函数将从本地缓存的目录中取出已有的游戏版本。
        :return: 返回缓存中的游戏版本列表，请注意：列表中的版本以字典形式存储。
        """
        game_versions_list: list = game_local_dict["game_list"]
        game_versions_list.sort(key=sort_, reverse=True)
        return game_versions_list

    def game_versions_add(self: int, version_num: str, version_name: str, java_version: str, java_path: str):
        """
        用于在game_versions.json中添加新的版本信息或Java信息，不给出值时将自动跳过。
        :param version_num: [可选]Minecraft版本号。
        :param version_name: [可选]Minecraft版本的自定义名称。
        :param java_version: [可选]Java版本号。
        :param java_path: [可选]Java路径。
        :return: 成功执行则返回True，出现错误则返回False。
        """
        game_versions_list = list(game_local_dict["game_list"])
        game_java_list = list(game_local_dict["java_list"])
        logger.Logger.info("查询本地存储的游戏列表成功，准备添加新记录。")
        confrim_change = False

        if version_name and version_num:
            for i in game_versions_list:
                if i["name"] == version_name:
                    logger.Logger.warning("以该自定义名称命名的版本已经存在，无法添加新版本记录。运行结束。")
                    return False
            add_dict = {"name": version_name, "version": version_num}
            game_versions_list.append(add_dict)
            game_local_dict["game_list"] = game_versions_list
            confrim_change = True
            logger.Logger.info("已处理新的游戏版本记录。")
        if java_version and java_path:
            for i in game_java_list:
                if i["version"] == java_version:
                    logger.Logger.warning("该版本的Java已经存在，无法添加同版本的另一个Java。")
                    if confrim_change:
                        game_versions = {"game_list": game_versions_list.sort(key=sort_, reverse=True), "java_list": game_java_list.sort(key=sort_, reverse=True)}
                        game_local_dict_ = open(file=config.game_versions_json_path, mode="w", encoding="utf-8")
                        game_local_dict_.write(json.dumps(game_versions))
                        game_local_dict_.close()
                        logger.Logger.info("已将游戏版本的相关新记录存入game_versions.json，运行结束。")
                        return True
                    else:
                        logger.Logger.info("无可填写的新记录，运行结束。")
                        return False

            add_dict = {"version": java_version, "path": java_path}
            game_java_list.append(add_dict)
            game_java_list.sort(key=sort_, reverse=True)
            game_local_dict["java_list"] = game_java_list
            confrim_change = True

        if confrim_change:
            game_versions = {"game_list": game_versions_list, "java_list": game_java_list}
            game_local_dict_ = open(file=config.game_versions_json_path, mode="w", encoding="utf-8")
            game_local_dict_.write(json.dumps(game_versions))
            game_local_dict_.close()
            logger.Logger.info("已将游戏版本和Java的相关新记录（也可能只有一个记录）存入game_versions.json。")
        else:
            logger.Logger.info("无需要添加的新纪录。")

        logger.Logger.info("运行结束。")
        return True


    def java_versions_list(self: int):
        """
        此函数将从本地缓存的目录中取出已保存的Java版本。
        :return: 返回缓存中的Java版本列表，请注意：列表中的版本以字典形式存储。
        """
        java_versions_list: list = game_local_dict["java_list"]
        for i in java_versions_list:
            j: str = i["path"]
            n: list = j.split("/")
            m: str = "\\"
            l: str = m.join(n)
            i["path"] = l
        return java_versions_list

    def local_setting_list(self: int):
        """
        此函数将从本地缓存的目录中取出已保存的启动参数，包括玩家名、UUID等。
        :return: 返回一部字典。
        """
        FCLsetting_list = dict(FCL_setting_dict["FCLsetting"])
        FCL_version_type = FCLsetting_list["FCLversion_type"]
        FCL_version_num = FCLsetting_list["FCLversion_num"]
        FCL_normal_setting = dict(FCLsetting_list["normal_setting"])
        FCL_setting_info = (FCL_version_type, FCL_version_num, FCL_normal_setting)
        return FCL_setting_info

    def saved_player_info(self: int, player_info_package: tuple):
        player_name_ = player_info_package[0]
        player_uuid_ = player_info_package[1]
        max_memory_ = player_info_package[2]
        min_memory_ = player_info_package[3]
        java_ = player_info_package[4]
        game_ = player_info_package[5]
        download_api_ = player_info_package[6]
        FCL_normal_setting = dict(FCL_setting_dict["FCLsetting"]["normal_setting"])
        FCL_normal_setting["player_name"] = player_name_
        FCL_normal_setting["player_uuid"] = player_uuid_
        FCL_normal_setting["game"] = game_
        FCL_normal_setting["java"] = java_
        FCL_normal_setting["max_memory"] = max_memory_
        FCL_normal_setting["min_memory"] = min_memory_
        FCL_normal_setting["download_api"] = download_api_
        FCL_setting_dict["FCLsetting"]["normal_setting"] = FCL_normal_setting
        saved_info = json.dumps(FCL_setting_dict)
        temp = open(file=config.FCL_setting_json_path, encoding="utf-8", mode="w")
        temp.write(saved_info)
        logger.Logger.info("玩家信息已缓存至文件。")
        temp.close()
        return None

    def read_features(self: int, version: str):
        features_dict = dict(versions_features_dict["features"])
        try:
            version_features = features_dict[version]
            feature_topic = str(version_features["topic"])
            feature_introduction = str(version_features["introduction"])
            return feature_topic, feature_introduction
        except:
            logger.Logger.warning("查询版本特色介绍失败。")
            return None
